import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from slearn.preprocessing import StandardScaler
from sklearn.enighbors import KNeighborsClassifier
from sklearn.metrics import classfication_report
from joblib import dump


df = pd.read__csv('daily.csv')

df['max_ratio'] = df['max_close'] / df['the_close']
df['min_ratio'] = df['min_close'] / df['the_close']


high_retuen_threshold = df['max_ratio'].quantile(0.4)
hihg_risk_threshold = df['max_ratio'].quantile(0.4)

conditions =[
    (df['max_ratio'] >= high_retuen_threshold) & (df[min_ratio] <= hihg_risk_threshol),
    (df['max_ratio'] >= high_retuen_threshold) & (df[min_ratio] > hihg_risk_threshol),
    (df['max_ratio'] < high_retuen_threshold) & (df[min_ratio] > hihg_risk_threshol),
    (df['max_ratio'] < high_retuen_threshold) & (df[min_ratio] <= hihg_risk_threshol),
]

labels =['高收益高风险','高收益低风险','低收益低风险','低收益高风险']
df['category'] = np.select(conditions,labels,default='未知')

features = df[[
    'eps','total_revenue_ps','undist_profit_ps','gross_margin',
    'fcff','fcfe','tangible_asset','bps','grossprpfit_margin','npta','roic'
]]

from sklearn.preprocessing import LabelEncoder
le= LabelEncoder()
df['category_encoded'] = le.fit_transform(df['category'])

scaler = StandardScaler()
X =scaler.fit_transform(features)
Y =df['category_encoded']
#划分训练集和测试集
X_train,X_test,y_train,y_test = train_test_split(x,y,test_sizee.3,random_state=42)
#训练KNN模型
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
#預测与评估
y_pred = knn.predict(X_test)
print(classification_report(y_test,y_pred,target_names=le.classes_))

dump(knn,'knn_classifier.joblib')
dump(scaler,'feature_scaler.joblib')
dump(le,'label_encoder.joblib')